﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSTDZ.ERP.Core.Repositories;
using XSTDZ.ERP.Domain.Models;
using XSTDZ.ERP.Application.DataContracts;
using AutoMapper;
using XSTDZ.ERP.Core.Generator;

namespace XSTDZ.ERP.Application.Implements
{
    public class WorkGroupServiceImpl : ApplicationServiceBase, IWorkGroupService
    {
         IRepository<WorkGroup> _workGroup;
         IRepository<Piece> _pieceRepository;
         IRepository<WagesBill> _wagesRepository;
         IRepository<WagesBillDetail> _wagesRepositoryDetail;
         public WorkGroupServiceImpl(IRepositoryContext repositoryContext, IRepository<WorkGroup> workGroup, IRepository<Piece> pieceRepository, IRepository<WagesBill> wagesRepository, IRepository<WagesBillDetail> wagesRepositoryDetail)
            : base(repositoryContext)
        {
            this._workGroup = workGroup;
            this._pieceRepository = pieceRepository;
            this._wagesRepository = wagesRepository;
            this._wagesRepositoryDetail = wagesRepositoryDetail;
        }


         public IList<WorkGroupDto> GetAllWorkGroup()
        {
            var workGroup = this._workGroup.GetAll(t=>t.Deleted!=1);

            return Mapper.Map<IList<WorkGroup>, IList<WorkGroupDto>>(workGroup.ToList());
        }


         public bool IsExistWorkGroupHeadman(WorkGroupDto workGroupDto)
         {
             if (workGroupDto.IsHeadman == 1)//判断是否是组长
             {
                 var wg = _workGroup.Get(t => t.IsHeadman == 1 && t.GroupName == workGroupDto.GroupName);
                 if (wg != null)
                 {
                     if (wg.Id == workGroupDto.Id)
                     {
                         return false;
                     }
                     return true;
                 }
             }
             return false;
         }

         public bool IsExist(WorkGroupDto workGroupDto)
         {
             return _workGroup.Exists(t => t.GroupName == workGroupDto.GroupName && t.UserID == workGroupDto.UserID&&t.Deleted==0);

         }

         public void AddWorkGroup(WorkGroupDto workGroupDto)
         {
             #region 只能保证只有一个组长
             if (workGroupDto.IsHeadman>0)
             {
                 var wlst = this._workGroup.GetAll(t => t.GroupName == workGroupDto.GroupName);
                 foreach (var item in wlst)
                 {
                     if (item.IsHeadman == 1)
                     {
                         item.IsHeadman = 0;
                     }
                 }
                 this._workGroup.Update(wlst);
             }
             #endregion
             var bill = Mapper.Map<WorkGroupDto, WorkGroup>(workGroupDto);
             bill.Id = (Guid)new SequentialIdentityGenerator().Next;
             this._workGroup.Add(bill);
             this.Context.Commit();
         }

         public void UpdateWorkGroup(WorkGroupDto workGroupDto)
         {
             var wlst = this._workGroup.GetAll(t => t.GroupName == workGroupDto.GroupName);
             foreach (var item in wlst)
             {
                 if (item.IsHeadman == 1)
                 {
                     item.IsHeadman = 0;
                 }
                 if (item.Id == workGroupDto.Id)
                 {
                     item.UserID = workGroupDto.UserID;
                     item.Remarks = workGroupDto.Remarks;
                     item.GroupName = workGroupDto.GroupName;
                     item.IsHeadman = workGroupDto.IsHeadman;
                 }
             }

             this._workGroup.Update(wlst);
             this.Context.Commit();
         }

         public void DeleteWorkGroup(Guid id)
         {
             var bill = _workGroup.GetByKey(id);
             bill.Deleted = 1;
             this._workGroup.Update(bill);
             this.Context.Commit();
         }
         public WorkGroupDto GetWorkGroup(Guid id)
         {
             var workGroup = this._workGroup.GetByKey(id);

             return Mapper.Map<WorkGroup, WorkGroupDto>(workGroup);
         }

         public IList<PieceDto> GetPiece(out int recordCount, int index, int pageSize)
         {
             var workGroup = this._pieceRepository.GetAll();
             recordCount = workGroup.Count();
             return Mapper.Map<IList<Piece>, IList<PieceDto>>(workGroup.ToList());
         }

         public Guid AddPiece(PieceDto pieceDto)
         {
             if (pieceDto.Id.HasValue && !pieceDto.Id.Equals(Guid.Empty))
             {
               return  UpdatePiece(pieceDto);
             }
             else
             {
                 var bill = Mapper.Map<PieceDto, Piece>(pieceDto);
                 bill.Id = (Guid)new SequentialIdentityGenerator().Next;
                 this._pieceRepository.Add(bill);
                 this.Context.Commit();

                 return bill.Id;
             }
         }

         public void Confirm(Guid billId)
         {
             var bill=this._pieceRepository.GetByKey(billId);
             if (bill != null)
             {
                 bill.BillState = 1;
                 this._pieceRepository.Update(bill);
                 this.Context.Commit();
             }
         }
         public Guid UpdatePiece(PieceDto pieceDto)
         {
             var bill = Mapper.Map<PieceDto, Piece>(pieceDto);
             this._pieceRepository.Update(bill);
             this.Context.Commit();
             return bill.Id;
         }

         public PieceDto GetPiece(Guid id)
         {
             var workGroup = this._pieceRepository.GetByKey(id);
             return Mapper.Map<Piece, PieceDto>(workGroup);
         }

         public IList<WagesBillDto> GetWagesBill(out int recordCount, int index, int pageSize)
         {
             var workGroup = this._wagesRepository.GetAll();
             recordCount = workGroup.Count();
             return Mapper.Map<IList<WagesBill>, IList<WagesBillDto>>(workGroup.ToList());
         }

         public void AddWagesBill(WagesBillDto wagesBillDto)
         {
             if (wagesBillDto.Id.HasValue && !wagesBillDto.Id.Equals(Guid.Empty))
             {
                 UpdateWagesBill(wagesBillDto);
             }
             else
             {
                 var bill = Mapper.Map<WagesBillDto, WagesBill>(wagesBillDto);
                 bill.Id = (Guid)new SequentialIdentityGenerator().Next;
                 this._wagesRepository.Add(bill);
                 this.Context.Commit();
             }
         }
         public void AddWagesBills(WagesBillDto wagesBillDto, IList<WagesBillDetailDto> wagesBillDtos)
         {
             List<Guid> workgroupIds = new List<Guid>();
             if (wagesBillDtos != null && wagesBillDtos.Count > 0)
             {
                 var bill = Mapper.Map<WagesBillDto, WagesBill>(wagesBillDto);
                 var billItems = Mapper.Map<IList<WagesBillDetailDto>, IList<WagesBillDetail>>(wagesBillDtos);
                 Guid billId = wagesBillDto.Id??Guid.Empty;
                 var isExist =billId.Equals(Guid.Empty)?false: _wagesRepository.Exists(t => t.Id == billId);
                 if (isExist)
                 {
                     var bs = _wagesRepository.GetByKey(billId);
                     bs.CreateTime = DateTime.Parse(bs.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"));
                     bs.UpdateDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                     bs.HeadmanAward = wagesBillDto.HeadmanAward;
                     bs.SumScrapMoney = wagesBillDto.SumScrapMoney;
                     bs.SumSubsidyMoney = wagesBillDto.SumSubsidyMoney;
                     bs.StartDate = wagesBillDto.StartDate;
                     bs.EndDate = wagesBillDto.EndDate;
                     bs.BillState = wagesBillDto.BillState;
                     bs.IsSettle = wagesBillDto.IsSettle;
                     //bs = Mapper.Map(bill, bs);
                     //bs.WagesBillDetails = Mapper.Map(billItems, bs.WagesBillDetails);
                     //  var items= Mapper.Map(billItems, bs.WagesBillDetails);
                     #region 更新明细
                     //处理明细
                     var productCheckBillDetails = Mapper.Map<IEnumerable<WagesBillDetailDto>, IEnumerable<WagesBillDetail>>(wagesBillDtos);

                     var updateItems = new List<WagesBillDetail>();
                     var insertItems = new List<WagesBillDetail>();
                     var itemIds = bs.WagesBillDetails.Select(d => d.Id).Cast<Guid>().ToList();

                     productCheckBillDetails.Each(
                         pd =>
                         {
                             if (itemIds.Contains(pd.Id))
                             {
                                 updateItems.Add(pd);
                             }
                             else
                             {
                                 pd.WagesBillID = bs.Id;
                                 pd.WorkGroupID = wagesBillDto.WorkGroupID;
                                 pd.Id = (Guid)new SequentialIdentityGenerator().Next;
                                 insertItems.Add(pd);
                             }
                         }
                         );
                     if (updateItems.Count() != 0)
                     {
                         foreach (var p in bs.WagesBillDetails)
                         {
                             foreach (var m in updateItems)
                             {
                                 if (m.Id == p.Id)
                                 {
                                     p.ScrapMoney = m.ScrapMoney;
                                     p.HeadmanAward = m.HeadmanAward;
                                     p.LiftMoney = m.LiftMoney;
                                     p.OtherMoney = m.OtherMoney;
                                     p.SubsidyMoney = m.SubsidyMoney;
                                     p.Wages = m.Wages;
                                     break;
                                 }
                             }
                         }

                         Mapper.Map(updateItems, bs.WagesBillDetails);
                     }
                     if (insertItems.Count() != 0)
                     {
                         this._wagesRepositoryDetail.Add(insertItems);
                     }
                     #endregion
                     workgroupIds = bs.WagesBillDetails.Select(t => t.WorkGroupID).ToList<Guid>();
                     _wagesRepository.Update(bs);
                 }
                 else
                 {
                     bill.Id = (Guid)new SequentialIdentityGenerator().Next;
                     bill.CreateTime = DateTime.Today;
                     billItems.Each(t =>
                     {
                         workgroupIds.Add(t.WorkGroupID);
                        // t.CreateDate = DateTime.Now;
                         t.WagesBillID = bill.Id;
                         t.Id = (Guid)new SequentialIdentityGenerator().Next;
                     });
                     bill.WagesBillDetails = billItems;
                     _wagesRepository.Add(bill);
                 }

                 #region 更新计件工资表
                 if (wagesBillDto.BillState == 1)
                 {
                     var pieces = this._pieceRepository.GetAll(t => workgroupIds.Contains(t.WorkGroupID)).ToList();
                     pieces.Each(t => t.IsSettleWage = 1);
                     this._pieceRepository.Update(pieces);
                 }
                 #endregion

                 this.Context.Commit();
             }
         }
         public bool IsExistWagesBillNo(string billNo)
         {
             return _wagesRepository.Exists(t => t.WagesBillNO == billNo);
         }
         public void UpdateWagesBill(WagesBillDto wagesBillDto)
         {
             var bill = Mapper.Map<WagesBillDto, WagesBill>(wagesBillDto);
             this._wagesRepository.Update(bill);
             this.Context.Commit();
         }

         public WagesBillDto GetWagesBill(Guid id)
         {
             var workGroup = this._wagesRepository.GetByKey(id);
             return Mapper.Map<WagesBill, WagesBillDto>(workGroup);
         }

         public string GetMaxBillNo()
         {
             var orderby = new OrderByParameter<WagesBill>(m => m.CreateTime, SortOrder.Descending);
             var billNo = this._wagesRepository.GetAll(1, 1, new[] { orderby }).FirstOrDefault();
             return billNo == null ? string.Empty : billNo.WagesBillNO;
         }
    }
}
